package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.key.RedisKeyConst;
import com.tanhua.commons.templates.HuaWeiUGCTemplate;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.PageResult;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mg.Publish;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.MoreDataVo;
import com.tanhua.domain.vo.PublishVo;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.ThreadLocalUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class PublishService {
    //注入ThreadLocalUtils
    @Autowired
    private ThreadLocalUtils threadLocalUtils;

    //订阅publishApi
    @Reference
    private PublishApi publishApi;
    //注入ossTemplate对象
    @Autowired
    private OssTemplate ossTemplate;
    //注入UserInfoApi
    @Reference
    private UserInfoApi userInfoApi;
    //注入redisTemplate对象
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //注入RockerMQ
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    //注入UserInfoService对象
    @Autowired
    private UserInfoService userInfoService;


    /**
     * 发布动态
     *
     * @param publishVo
     * @param multipartFiles
     */
    public void publishData(PublishVo publishVo, MultipartFile[] multipartFiles) {
        try {
            //1,创建用于存储图片地址的集合对象
            ArrayList<String> imgAll = new ArrayList<>();
            //2,遍历图片数组对象
            for (MultipartFile multipartFile : multipartFiles) {
                //调用方法 传入图片文件 返回文件的访问地址
                String publishPicUrl = userInfoService.getUploadUrlByFdfs(multipartFile);
                //4,将图片地址存入集合对象
                imgAll.add(publishPicUrl);
            }
            //debug发现id没有赋值
            publishVo.setId(threadLocalUtils.getUserId());
            //5,将集合对象封装到vo对象
            publishVo.setImages(imgAll);
            //6,调用APi接口 传入vo对象
            String publishId = publishApi.publishData(publishVo);
            //7.发送消息 进行动态审核
            rocketMQTemplate.convertAndSend("ysx_dynamicReview",publishId);
        } catch (IOException e) {
            e.printStackTrace();
            throw new TanHuaException(ErrorResult.error());
        }
    }

    /**
     * 接受好友动态
     */
    public PageResult<MoreDataVo> friendData(Integer page, Integer pagesize) {
        //1.1获取到当前用户的Id
        Long currentId = threadLocalUtils.getUserId();
        //1.2根据用户Id 查询monggo数据库  返回PageResult<publish>对象
        PageResult<Publish> publishPageResult = publishApi.queryPublishById(currentId, page, pagesize);
        //调用公共方法 传入publishPageResult对象 返回PageResult<MoreDataVo>
        return convertAndEncapsulateData(publishPageResult);
    }

    /**
     * 推荐随机动态
     */
    public PageResult<MoreDataVo> recommendData(Integer page, Integer pagesize) {
        //1.1获取到当前用户的Id
        Long currentId = threadLocalUtils.getUserId();
        //1.2根据用户Id 查询monggo数据库  返回PageResult<pulish>对象
        PageResult<Publish> publishPageResult = publishApi.queryPublishById2(currentId, page, pagesize);
        //调用公共方法 传入publishPageResult对象 返回PageResult<MoreDataVo>
        return convertAndEncapsulateData(publishPageResult);

    }

    /**
     * 我的动态
     */
    public PageResult<MoreDataVo> MyPublishData(Integer page, Integer pagesize,Long uid) {
        //1.1获取到当前用户的Id
        Long currentId = threadLocalUtils.getUserId();
        //1.2根据用户Id 查询monggo数据库  返回PageResult<pulish>对象
        PageResult<Publish> publishPageResult = publishApi.MyPublishData(uid, page, pagesize);
        //调用公共方法 传入publishPageResult对象 返回PageResult<MoreDataVo>
        return convertAndEncapsulateData(publishPageResult);
    }

    /**
     * 点赞是否高亮显示的判断
     */
    public void isLike(MoreDataVo moreDataVo,Integer id) {
        String key=RedisKeyConst.LIKE_STATUS+id+"_"+moreDataVo.getId();
        //判断redis中是否存在这个点过赞的键
        if(!StringUtils.isEmpty(redisTemplate.opsForValue().get(key))){
            moreDataVo.setHasLiked(1);
        }
        else{
            moreDataVo.setHasLiked(0);
        }
    }

    /**
     * 喜欢是否高亮显示的判断
     */
    public void isLove(MoreDataVo moreDataVo,Integer id) {
        String key=RedisKeyConst.LOVE_STATUS+id+"_"+moreDataVo.getId();
        //判断redis中是否存在这个喜欢的键
        if(!StringUtils.isEmpty(redisTemplate.opsForValue().get(key))){
            moreDataVo.setHasLoved(1);
        }
        else{
            moreDataVo.setHasLoved(0);
        }
    }
    /**
     * 转换并且封装pageResult对象
     * @param publishPageResult
     */
    private PageResult<MoreDataVo> convertAndEncapsulateData(PageResult<Publish> publishPageResult) {
        //获取到所有的publish对象
        List<Publish> publishList = publishPageResult.getItems();
        List<MoreDataVo> moreDataVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(publishList)) {
            //1.4遍历items属性
            for (Publish publish : publishList) {
                //创建一个MoreData对象
                MoreDataVo moreDataVo = new MoreDataVo();
                //1.5获得itmes属性的userId
                Long userId = publish.getUserId();
                //1.6根据userId查询userinfo表 返回userinfo对象
                UserInfo userInfo = userInfoApi.findUserInfoByID(userId);
                //1.7将userinfo的属性复制到vo属性上
                BeanUtils.copyProperties(userInfo, moreDataVo);
                //1.8将publish属性复制到vo属性上
                BeanUtils.copyProperties(publish, moreDataVo);
                //1.9将补全其他的属性
                //将发布id装成String格式 存储
                moreDataVo.setId(publish.getId().toHexString());
                //判断tags是否为null
                if (!StringUtils.isEmpty(userInfo.getTags())) {
                    moreDataVo.setTags(userInfo.getTags().split(","));
                }
                //图片属性对应不上 单独设置
                moreDataVo.setImageContent(publish.getMedias().toArray(new String[]{}));
                //将publish的毫秒值转换成日期格式
                String format = RelativeDateFormat.format(new Date(publish.getCreated()));
                moreDataVo.setCreateDate(format);
                //假数据 距离
                moreDataVo.setDistance("1米");
                //发布动态的用户Id
                moreDataVo.setUserId(userId.intValue());
                //是否点赞
                isLike(moreDataVo,threadLocalUtils.getUserId().intValue());
                //是否喜欢
                isLove(moreDataVo,threadLocalUtils.getUserId().intValue());
                //将moreDataVo对象添加到moreDataVoList
                moreDataVoList.add(moreDataVo);
            }
            //创建一个PageResult<MoreDataVo>对象
            PageResult<MoreDataVo> moreDataVoPageResult = new PageResult<>();
            BeanUtils.copyProperties(publishPageResult, moreDataVoPageResult);
            moreDataVoPageResult.setItems(moreDataVoList);
            return moreDataVoPageResult;
        }
        return null;
    }
}
